apply
function is a special way of calling
functions where some or all of the arguments that you want to
send to that function are available in a collection such as an
array. It takes the arguments out of the collection and
"applies" the function to them as if you had written them down
explicitly in a normal function call.apply function otherArgs collectionOfArgsIn using
apply
, otherArgs can be any
number of interim arguments. The final argument to
apply
, however, must be a collection such as an
array (or an expression that results in a linear collection).
That array contains any remaining arguments to the
function, and can contain any number of elements,
including none #()
.
The apply
function is often useful when you are
calling a function that defines rest arguments from within
another function that also defines rest arguments. It allows
you to "spread out" an array of arguments into a function
call, regardless of how many elements the original array had
in it.
function addEmUp #rest args -> (
local sum := 0
for i in args do sum := sum + i
return sum
)
global a := #(1,4,9,16)
global b := 1 to (a.size)
myArgs := merge a b
-- use apply to call a function with rest arguments
apply addEmUp myArgs
40
A typical use of apply
is in initialization
(init
) methods for classes and objects. All
init
methods define rest arguments, and you are
required to pass them along to a superclass's
init
methods. For more information on
initialization methods and apply
, see Chapter 6, "Defining Classes and
Objects."
This document is part of the ScriptX Language Guide, one of the volumes of the ScriptX Technical Reference Series. ScriptX is developed by the ScriptX Engineering Team at Apple Computer, successor to the Kaleida Engineering Team at Kaleida Labs, Inc.